// pages/person/supplier/index.js
const ajax = require('../../../utils/quest.js');
const util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    max: 300, //最多字数 (根据自己需求改变) 
    currentWordNumber: 0,
    showModalStatus: false,
    cateList: [],
    selectList: [],
    personalPhotolist: [],
    arrList: [],
    categoryPid: [],
    categoryPidList: [],
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getTree()
    this.getFarmerUserInfo()
  },
  //字数限制 
  inputs: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);
    this.setData({
      currentWordNumber: len //当前字数 
    });
    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
  },
  bandSpecialty: function () {
    this.showModal()
  },
  // 显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  getTree: function () {
    ajax.sendRequest('/category/getCategoryTree', 'get').then(res => {
      const {
        categoryVOList
      } = res.data
      const isList = []
      for (var i = 0; i < categoryVOList.length; i++) {
        for (var j = 0; j < categoryVOList[i].sonCategoryList.length; j++) {
          categoryVOList[i].sonCategoryList[j].isSelected = false
        }
        isList.push(categoryVOList[i])
      }
      this.setData({
        cateList: isList,
      })
    })
  },
  bandCancel() {
    this.hideModal()
  },
  bandDetermine() {
    const {
      selectList,
      cateList,
    } = this.data
    const selectLists = []
    for (var k = 0; k < cateList.length; k++) {
      cateList[k].sonCategoryList.map(i => {
        if (i.isSelected == true) {
          selectLists.push(i)
        }
      })
    }
    const categoryIds = selectLists.map(item => {
      return item.id
    })
    const categoryName = selectLists.map(item => {
      return item.categoryName
    })
    this.setData({
      specialty: categoryName.join(','),
      cateList: cateList,
      categoryIds: categoryIds
    })
    this.hideModal()
  },
  addressRelicList: function (e) {
    let id = e.currentTarget.dataset.id;
    let item = this.data.cateList.map(i => {
      const idItem = i.sonCategoryList.filter(j => {
        return j.id == id
      })
      return idItem
    })
    const {
      selectList,
      categoryPidList
    } = this.data
    for (var k = 0; k < item.length; k++) {
      item[k].map(i => {
        i.isSelected = !i.isSelected
        if (i.isSelected == true) {
          selectList.push(i)
          categoryPidList.push(i.pid)
        }
      })
    }
    this.setData({
      cateList: this.data.cateList,
      selectList: selectList,
      categoryPidList: util.arrDeduplication(categoryPidList)
    })
  },
  // 删除
  delImages: function (e) {
    const {
      personalPhotolist
    } = this.data
    const that = this
    const index = e.currentTarget.dataset.item
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          personalPhotolist.splice(index, 1)
          that.setData({
            personalPhotolist: personalPhotolist
          })
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
      }
    })
  },
  // 上传
  uploadImages: function () {
    const than = this
    const {
      arrList,
      personalPhotolist
    } = than.data
    wx.chooseImage({
      count: 1,
      sizeType: ['original'], //原图
      sourceType: ['album', 'camera'], //支持选取图片
      success(res) {
        arrList.push(res.tempFiles[0])
        ajax.upLoadFiles(res.tempFiles[0].path).then(res => {
          // const imgUrl = res
          const personalPhoto = {
            'picUrl': res
          }
          personalPhotolist.push(personalPhoto)
          if (res) {
            than.setData({
              picList: arrList,
              personalPhotolist: personalPhotolist
            })
          } else {
            return wx.showToast({
              title: '系统内部错误，请联系管理员',
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 我的地址
  bindRegionChange: function (e) {
    var adressArr = e.detail.value;
    if (adressArr[1] == '北京市' || adressArr[1] == '天津市' || adressArr[1] == '上海市' || adressArr[1] == '重庆市') {
      adressArr[1] = '市辖区'
    }
    this.getArea(adressArr.join(","));
    this.setData({
      region: e.detail.value.join('')
    })
  },
  getArea: function (strUrl) {
    var that = this;
    var strUrls = {
      names: strUrl
    }
    ajax.sendRequest("/area/getAreaByNames", 'get', strUrls)
      .then(function (response) {
        var resArr = response.data.areaVOS;
        if (resArr.length >= 3) {
          var province = response.data.areaVOS[0].value;
          var city = undefined;
          var district = undefined;
          for (var i = 0; i < resArr.length; i++) {
            if (resArr[i].pid == province) {
              city = resArr[i].value;
            }
            if (resArr[i].pid == city) {
              district = resArr[i].value;
            }

          }
          var regionId = {
            province: province,
            city: city,
            district: district
          }
          that.setData({
            myRegionId: regionId
          })

        } else if (resArr.length == 0) {
          wx.showModal({
            title: '提示',
            content: '该平台目前不支持您所选区域！',
          })
        }
      }, function (error) {})
  },
  formSubmitLogin(e) {
    this.setData({
      personalInformation: e.detail.value
    })
    this.save()
  },
  // 提交函数
  save() {
    const {
      personalInformation,
      specialty,
      myRegionId,
      personalPhotolist,
      categoryIds,
      userInfo,
      categoryPidList,
      region
    } = this.data
    if (!personalInformation.fullName) {
      return wx.showToast({
        icon: "none",
        title: '请填写真实姓名',
      })
    } else if (!personalInformation.telephone) {
      return wx.showToast({
        icon: "none",
        title: '请填写联系电话',
      })
    } else if (!personalInformation.merchantName) {
      return wx.showToast({
        icon: "none",
        title: '请填写商户名称',
      })
    } else if (!personalInformation.businessHours) {
      return wx.showToast({
        icon: "none",
        title: '请填写营业时间',
      })
    } else if (!specialty) {
      return wx.showToast({
        icon: "none",
        title: '请选择主营商品',
      })
    } else if (!myRegionId) {
      return wx.showToast({
        icon: "none",
        title: '请选择选择地址',
      })
    } else if (!personalInformation.address) {
      return wx.showToast({
        icon: "none",
        title: '请填写具体地址',
      })
    } else if (!personalInformation.introduce) {
      return wx.showToast({
        icon: "none",
        title: '请填写自我介绍',
      })
    }
    //  else if (!personalPhotolist.length) {
    //   return wx.showToast({
    //     icon: "none",
    //     title: '请上传图片',
    //   })
    // } 
    else {
      const reqBody = {
        id: userInfo.id ? userInfo.id : null,
        ...personalInformation,
        ...myRegionId, //省市区
        categoryIds: categoryPidList.concat(categoryIds), // 分类id列表
        providerPicList: personalPhotolist, //服务商图片列表
        commodity: specialty,
        position: region.join(''),
        categoryPid: ''
      }
      ajax.sendRequest('/provider/saveProviderUserInfo', 'post', reqBody).then(res => {
        wx.showModal({
          title: '提示',
          content: '保存成功',
          success(res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      })
    }
  },
  getFarmerUserInfo() {
    ajax.sendRequest('/provider/providerUserInfo', 'get').then(res => {
      const userInfo = res.data.providerInformationVO
      if (userInfo == null) {
        return
      } else {
        const {
          cateList
        } = this.data
        const categoryIds = (userInfo || userInfo.categoryIds) == null ? [] : userInfo.categoryIds // 后台选中的id
        for (var k = 0; k < cateList.length; k++) {
          cateList[k].sonCategoryList.forEach(i => {
            if (categoryIds) {
              categoryIds.forEach(j => {
                if (j == i.id) {
                  i.isSelected = true
                }
              });
            }
          })
        }
        this.setData({
          cateList: this.data.cateList,
          userInfo: userInfo,
          fullName: userInfo.fullName,
          telephone: userInfo.telephone,
          merchantName: userInfo.merchantName,
          businessHours: userInfo.businessHours,
          specialty: userInfo.commodity,
          categoryIds: userInfo.categoryIds,
          myRegionId: {
            province: userInfo.province,
            city: userInfo.city,
            district: userInfo.district
          },
          region: userInfo.provinceName ? [userInfo.provinceName, userInfo.cityName, userInfo.districtName] : null,
          address: userInfo.address,
          introduce: userInfo.introduce,
          personalPhotolist: userInfo.providerPicList ? userInfo.providerPicList : []
        })
      }

    }).catch(err => {
      console.log("err", err);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})